package com.imooc.ad.index;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.PriorityOrdered;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description: TODO
 * @ClassName: DateTable
 * @Author: zhangzhongyu
 * @Date: 2019-10-15 21:19
 * @Version: 1.0
 */
@Component
public class DateTable implements ApplicationContextAware, PriorityOrdered {

    private static ApplicationContext applicationContext;

    public static final Map<Class, Object> dataTableMap
            = new ConcurrentHashMap<>();

    // 通过继承这个类，可以得到Spring中初始化的各个组件和各个Bean
    @Override
    public void setApplicationContext(
            ApplicationContext applicationContext) throws BeansException {
        // 是ApplicationContextAware实现注入的
        DateTable.applicationContext = applicationContext;
    }

    // 会在Spring初始化所有的JavaBean，继承PriorityOrdered可以决定初始化的顺序
    // 会优先初始化排好序列的JavaBean，再初始化其他的
    @Override
    public int getOrder() {
        // 最高优先级，值越小，优先级越高
        return PriorityOrdered.HIGHEST_PRECEDENCE;
    }

    // 根据索引类型获取到索引服务类
    @SuppressWarnings("all")
    public static <T> T of(Class<T> clazz) {
        T instance = (T) dataTableMap.get(clazz);
        if (null != instance) {
            return instance;
        }

        dataTableMap.put(clazz, bean(clazz));
        return (T) dataTableMap.get(clazz);
    }

    @SuppressWarnings("all")
    private static <T> T bean(String beanName) {
        return (T) applicationContext.getBean(beanName);
    }

    @SuppressWarnings("all")
    private static <T> T bean(Class clazz) {
        return (T) applicationContext.getBean(clazz);
    }
}
